<!-- URL项目菜单 -->
<template>
    <div class="custom__container">
        <tierproce :data="tiers" prefix="url" :depth="0" />
    </div>
</template>

<script lang="ts" setup>
    import { ref } from 'vue'
    import { useRouter } from 'vue-router'

    // 组件
    import Tierproce from './tierproce.vue'

    // 类型
    import type { RouteInfo, RouteTier, Modules, RouteRecordRaw } from './type.d'

    // 获取路由实例
    const router = useRouter()

    // 处理路由模块
    const tiers = ref<RouteTier>({})

    // 递归创建嵌套层级
    const createNestedTiers = (tiers: RouteTier, tierArr: string[], info: RouteInfo): void => {
        // 基础情况：如果路径为空，返回
        if (tierArr.length === 0) return;

        const [currentKey, ...remainingPath] = tierArr;

        // 确保当前键存在
        if (!tiers[currentKey]) {
            tiers[currentKey] = {};
        }

        // 如果是最后一层，添加路由信息
        if (remainingPath.length === 0) {
            for (const key in info) {
                tiers[currentKey][key] = info[key]
            }
            return;
        }

        // 递归处理剩余路径
        createNestedTiers(tiers[currentKey], remainingPath, info);
    };

    // 导入所有模块路由
    const modules = import.meta.glob<Modules & RouteRecordRaw>([
        '@/modules/**/*.router.ts',
        '@/modules/**/*.router.js',
    ], { eager: true })

    // 遍历模块路由
    Object.values(modules).forEach((module) => {
        const moduleRoutes = module.default || module
        if (!import.meta.env.DEV && moduleRoutes.isDemo === true) return
        if (!moduleRoutes.meta) return
        if (!Array.isArray(moduleRoutes.meta.tier) || moduleRoutes.meta.tier.length === 0) return

        // 创建嵌套层级
        createNestedTiers(tiers.value, moduleRoutes.meta.tier, {
            path: moduleRoutes.path!,
            title: moduleRoutes.meta.title as string,
            url: location.origin + router.resolve(moduleRoutes.path!).href
        })
    })
</script>

<style lang="scss" scoped>

    // 自定义容器
    .custom__container {
        padding: 10px;
        box-sizing: border-box;
    }
</style>